package com.jinyang.jetpackdemo.bean

import java.io.Serializable

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/12/3
 * @Description:
 */
object KSingleton : Serializable { //实现Serializable序列化接口，通过私有、被实例化的readResolve方法控制反序列化
    fun doSomething() {
        println("do some thing")
    }

    private fun readResolve(): Any {//防止单例对象在反序列化时重新生成对象
        return KSingleton//由于反序列化时会调用readResolve这个钩子方法，只需要把当前的KSingleton对象返回而不是去创建一个新的对象
    }
}

//在Kotlin中使用KSingleton
fun main(args: Array<String>) {
//    KSingleton.doSomething()//像调用静态方法一样，调用单例类中的方法
//    KLazilySingleton.getInstance().doSomething()
    //在Kotlin中调用，直接通过KLazilyDCLSingleton类名调用instance
//    KLazilyDCLSingleton.instance.doSomething()
//    KOptimizeSingleton.getInstance().doSomething()
    KEnumSingleton.INSTANCE.doSomeThing()
}

enum class KEnumSingleton {
    INSTANCE;

    fun doSomeThing() {
        println("do some thing")
    }
}


class KOptimizeSingleton private constructor() : Serializable {
    //private constructor()构造器私有化
    companion object {
        @JvmStatic
        fun getInstance(): KOptimizeSingleton {//全局访问点
            return SingletonHolder.mInstance
        }
    }

    fun doSomething() {
        println("do some thing")
    }

    private object SingletonHolder {
        //静态内部类
        val mInstance: KOptimizeSingleton = KOptimizeSingleton()
    }

    private fun readResolve(): Any {//防止单例对象在反序列化时重新生成对象
        return SingletonHolder.mInstance
    }
}

class KLazilySingleton private constructor() : Serializable {
    fun doSomething() {
        println("do some thing")
    }

    companion object {
        private  var mInstance: KLazilySingleton? = null
            get() {
                return field ?: KLazilySingleton()
            }

        @JvmStatic
        @Synchronized//添加synchronized同步锁
        fun getInstance(): KLazilySingleton {
            return requireNotNull(mInstance)
        }
    }

    //防止单例对象在反序列化时重新生成对象
    private fun readResolve(): Any {
        return getInstance()
    }
}

class KLazilyDCLSingleton private constructor() : Serializable {//构造器私有化

    fun doSomething() {
        println("do some thing")
    }

    private fun readResolve(): Any {//防止单例对象在反序列化时重新生成对象
        return instance
    }

    companion object {
        @JvmStatic
        //使用lazy属性代理，并指定LazyThreadSafetyMode为SYNCHRONIZED模式保证线程安全
        val instance: KLazilyDCLSingleton by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { KLazilyDCLSingleton() }
    }
}





